package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
@Slf4j
public class CacheClient {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    // 设置key value 过期时间
    public void set(String key, Object value, Long expireTime, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), expireTime, unit);
    }

    // 设置逻辑过期时间
    public void setWithLogicalExpire(String key, Object value, Long expireTime, TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(expireTime)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    public <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID, R> fallback,
                                           Long expireTime, TimeUnit unit) {
        String key = keyPrefix + id;
        String jsonString = stringRedisTemplate.opsForValue().get(key);
        // value存在 直接返回数据
        if (StrUtil.isNotBlank(jsonString)) {
            return JSONUtil.toBean(jsonString, type);
        }

        // 不是null说明有值，但是前面判断value不存在，说明是空串“”，说明之前触发了缓存穿透，暂时设置了空串
        if(jsonString != null) {
            return null;
        }

        R r = fallback.apply(id);
        // 得到的数据是空 说明数据库中没有数据 导致缓存穿透 给缓存的value设置空值
        if (r == null) {
            set(key,"", RedisConstants.CACHE_NULL_TTL, TimeUnit.SECONDS);
            return null;
        }

        // 能到这里说明有值，则设置有效数据的缓存
        this.set(key, r, expireTime, unit);

        return r;
    }


    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public  <R,ID> R queryWithLogicExpire(String keyPrefix, ID id, Class<R> type, Function<ID, R> fallback, Long expireTime, TimeUnit unit) {
        String key = keyPrefix + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 不存在 直接返回null
        if (StrUtil.isBlank(shopJson)) {
            return null;
        }
        // 获取数据
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime dataExpireTime = redisData.getExpireTime();
        // 判断是否过期 如果是当前时间之后，说明没过期 直接返回数据
        if (dataExpireTime.isAfter(LocalDateTime.now())) {
            return r;
        }

        // 已过期 缓存重建 获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean lock = tryLock(lockKey);
        // 成功获取到互斥锁，开启新线程进行缓存重建逻辑
        if (lock) {
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    R newR = fallback.apply(id);
                    setWithLogicalExpire(key, newR, expireTime, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(lockKey);
                }
            });
        }

        // 返回过期的数据
        return r;
    }

    // 上互斥锁
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        // 使用工具类对Boolean进行判断， 防止自动拆箱导致Boolean出现null
        return BooleanUtil.isTrue(flag);
    }
    // 解锁
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

}
